package unq.tpi.persistencia.performanceEj.daos;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import unq.tpi.persistencia.performanceEj.model.Department;
import unq.tpi.persistencia.util.SessionManager;

public class DepartmentDAO {

	public Department getByName(final String name) {
		Session session = SessionManager.getSession();
		return (Department) session
				.createQuery("from Department where name = :name")
				.setParameter("name", name).uniqueResult();
	}

	public Department getByCode(String num) {
		Session session = SessionManager.getSession();
		return (Department) session.get(Department.class, num);
	}

	public Department getByCodeForListadoPagosPorDepto(String num) {
		
//		Query query = SessionManager.getSession().createQuery("from Department where dept_no = :num inner join Department.employees");
//		query.setParameter("num", num);
//		query.setParameter("to_date", "9999-01-01");
//		
//		return  (Department) query.list().get(0);
		
		Session session = SessionManager.getSession();
		Criteria departamento = session.createCriteria(Department.class);
		departamento.add(Restrictions.eq("number", num));
		
		Criteria empleados =  departamento.createCriteria("employees" , "employees");
		empleados.createCriteria("salaries" , "salaries").add( Restrictions.sqlRestriction("{alias}.to_date = '9999-01-01'"));
		empleados.setFetchMode("titles", FetchMode.JOIN);
		
		//empleados.createAlias("titles", "titles");	//Todavia no anda poniendo la restriccion por titulos
		//empleados.add(Restrictions.sqlRestriction("titles.to_date = '9999-01-01'"));
		return (Department) departamento.list().get(0);
	
	}

	public Department getByCodeForListadoPagosPorDepto2(String num) {
		
		Session session = SessionManager.getSession();
		Criteria departamento = session.createCriteria(Department.class);
		departamento.add(Restrictions.eq("number", num));
		//departamento.setFetchMode("employees", FetchMode.JOIN);
		departamento.setReadOnly(true);
				
		Criteria empleados =  departamento.createCriteria("employees" , "employees");
		//empleados.setFetchSize(1000);								//afecta poco
		empleados.setReadOnly(true);
		//empleados.setFetchMode("salaries", FetchMode.JOIN);		//afecta poco
		empleados.setFetchMode("titles", FetchMode.JOIN);			//afecta poco pero es util para que no tire un select por cada titulo
		
		Criteria salarios=empleados.createCriteria("salaries" , "salaries");
		salarios.add( Restrictions.sqlRestriction("{alias}.to_date = '9999-01-01'"));
		//salarios.setFetchSize(1000);								//afecta poco
		salarios.setReadOnly(true);
		
		return (Department) departamento.list().get(0);
	
	}
	
		
	
	@SuppressWarnings("unchecked")
	public List<Department> getAll() {
		Session session = SessionManager.getSession();
		return session.createCriteria(Department.class).list();
	}

}
